<?php

namespace app\admin\logic;

use app\admin\validate\GenerateValidate;
use support\Backend\BackendLogic;
use support\Container;
use support\Db;
use support\Exception\ApiException;
use support\Service\GenerateConfigService;
use support\Strategy\FileStrategy;
use support\Strategy\Generate\Make;

class GenerateLogic extends BackendLogic
{


    public function __construct()
    {
        $this->service = Container::get(GenerateConfigService::class);
    }

    public function getList(): array
    {
        // 查询SQL
        $sql = "SHOW TABLE STATUS WHERE 1";
        // 请求参数
        $param = request()->all();
        $name = $param['name'] ?? '';
        $comment = $param['comment'] ?? '';
        $limit = $param['limit'] ?? 10;
        $page = $param['page'] ?? 1;
        if ($name) {
            $sql .= " AND NAME like \"%{$name}%\" ";

        }
        if ($comment) {
            $sql .= " AND COMMENT like \"%{$comment}%\" ";
        }
        $list = Db::select($sql);
        $startIndex = ($page - 1) * $limit;
        // 切片操作，提取指定范围内的元素
        $data = array_slice(toArray($list), $startIndex, $limit);

        $data = array_map('array_change_key_case', $data);
        return message(['list' => $data, 'total' => count($list)]);

    }

    /**
     * 获取表字段列表
     * @return array
     */
    public function getColumnList(): array
    {
        $name = request()->post('name');
        $data = [];
        if (!$name) return message($data);
        $info = Db::select("SHOW TABLE STATUS where  NAME ='$name'");
        $list = Db::select("SELECT COLUMN_NAME,COLUMN_DEFAULT,DATA_TYPE,COLUMN_TYPE,COLUMN_COMMENT FROM information_schema.`COLUMNS` where TABLE_SCHEMA = '" . env('DB_NAME') . "' AND TABLE_NAME = '{$name}'");
        if (!$list) return message($data);
        $list = toArray($list);
        $info = toArray($info);
        $config_info = $this->service->getInfoByWhere(['table_name' => str_replace(env('DB_PREFIX'), '', $name)]);
        $gen_base_config = json_decode($config_info['gen_base'] ?? '', true) ?? [];
        $gen_base_list_config = json_decode($config_info['gen_base_config'] ?? '', true) ?? [];
        $gen_base_list = array_column($gen_base_list_config['list'] ?? [], null, 'column_name');

        $gen_edit_config = json_decode($config_info['gen_edit_config'] ?? '', true) ?? [];
        $gen_edit_list = array_column($gen_edit_config['list'] ?? [], null, 'column_name');
        $gen_edit_form = $gen_edit_config['form'] ?? [];

        $gen_del_config = json_decode($config_info['gen_del_config'] ?? '', true) ?? [];
        $gen_del_form = $gen_del_config['form'] ?? [];

        $gen_search_config = json_decode($config_info['gen_search_config'] ?? '', true) ?? [];
        $gen_search_list = $gen_search_config['list'] ?? [];
        $base = [
            'table_name' => $name,
            'table_comment' => $info[0]['Comment'] ?? '',
            'table_prefix' => config('database.connections.mysql.prefix') ?? '',
            'note' => !empty($gen_base_config['note']) ? $gen_base_config['note'] : ($info[0]['Comment'] ?? ''),
            'author' => !empty($gen_base_config['author']) ? $gen_base_config['author'] : 'BhAdmin',
            'time' => !empty($gen_base_config['time']) ? $gen_base_config['time'] : date('Y-m-d'),
        ];
        $baseList = $editList = [];
        $sort=0;
        foreach ($list as $item) {
            // 表名称
            $child_sort=++$sort;
            $table_name = $name;
            $column_name = $item['COLUMN_NAME'];
            $column_default = $item['COLUMN_DEFAULT'];
            $data_type = ucfirst($item['DATA_TYPE']);
            $column_comment = $item['COLUMN_COMMENT'];
            $gen_base_list_info = $gen_base_list[$column_name] ?? [];
            $gen_edit_list_info = $gen_edit_list[$column_name] ?? [];
            $column = [
                'table_name' => $table_name,
                'column_name' => $column_name,
                'column_default' => $column_default,
                'data_type' => $data_type,
                'column_comment' => $column_comment,
                'is_show' => $gen_base_list_info['is_show'] ?? true,
                'title' => !empty($gen_base_list_info['title']) ? $gen_base_list_info['title'] : $column_comment,
                'column_as' => !empty($gen_base_list_info['column_as']) ? $gen_base_list_info['column_as'] : $column_name,
                'width' => !empty($gen_base_list_info['width']) ? $gen_base_list_info['width'] : '',
                'dict_code' => !empty($gen_base_list_info['dict_code']) ? $gen_base_list_info['dict_code'] : '',
                'sort' => $gen_base_list_info['sort'] ?? $child_sort
            ];


            $edit = [
                'column_name' => $column_name,
                'column_comment' => $column_comment,
                'data_type' => $data_type,
                'column_default' => $column_default,
                'show_add' => $gen_edit_list_info['show_add'] ?? true,
                'show_edit' => $gen_edit_list_info['show_edit'] ?? true,
                'is_required' => $gen_edit_list_info['is_required'] ?? true,
                'dict_code' => !empty($gen_edit_list_info['dict_code']) ? $gen_edit_list_info['dict_code'] : '',
                'form_component' => !empty($gen_edit_list_info['form_component']) ? $gen_edit_list_info['form_component'] : '',
                'title' => !empty($gen_edit_list_info['title']) ? $gen_edit_list_info['title'] : $column_comment,
                'sort' => $gen_edit_list_info['sort'] ?? $child_sort

            ];
            $baseList[] = $column;
            $editList[] = $edit;
        }
        $data['base'] = $base;
        $data['base_list'] = multiSortArray($baseList, 'sort');;
        $data['edit_config']['from'] = [
            'is_show' => $gen_edit_form['is_show'] ?? 1,
            'open_type' => $gen_edit_form['open_type'] ?? 'modal',// modal| drawer
            'open_width' => $gen_edit_form['open_width'] ?? 500,
            'rows_num' => $gen_edit_form['rows_num'] ?? 1
        ];
        $data['edit_config']['list'] = multiSortArray($editList, 'sort');
        $data['delete_config']['from'] = [
            'is_show' => $gen_del_form['is_show'] ?? 1,
            'delete_type' => $gen_del_form['delete_type'] ?? [1],
        ];
        $data['search_config']['list'] = $gen_search_list;

        return message($data);
    }


    /**
     * 设置配置
     * @return array
     */
    public function setColumn(): array
    {
        $data = request()->post();
        $validate = new GenerateValidate();
        if (!$validate->check($data)) throw new ApiException($validate->getError());
        $table_name = str_replace($data['gen_base']['table_prefix'], '', $data['gen_base']['table_name']);
        //判断是否有数据
        $info = $this->service->getInfoByWhere(['table_name' => $table_name]);
        $save['table_name'] = $table_name;
        $save['gen_base'] = json_encode($data['gen_base'], JSON_UNESCAPED_UNICODE);
        $save['gen_base_config'] = json_encode(['list' => $data['gen_base_list']], JSON_UNESCAPED_UNICODE);
        $save['gen_edit_config'] = json_encode(['form' => $data['gen_edit_form'], 'list' => $data['gen_edit_list']], JSON_UNESCAPED_UNICODE);
        $save['gen_del_config'] = json_encode(['form' => $data['gen_del_form']], JSON_UNESCAPED_UNICODE);
        $save['gen_search_config'] = json_encode(['list' => $data['gen_search_list']], JSON_UNESCAPED_UNICODE);
        if (!$info) {
            $this->service->add($save);
        } else {
            $this->service->save($save, $info['id']);
        }
        return message($data);
    }

    public function createCode($name)
    {

        if (!$name) throw new ApiException('请传入表名');

        //判断是否生成配置
        $info = $this->service->getInfoByWhere(['table_name' => $name]);
        if (!$info) throw new ApiException('请先生成代码配置');
        $make = new Make($name);
        $base_config = json_decode($info['gen_base'], true) ?? [];
        $gen_base_config = json_decode($info['gen_base_config'], true) ?? [];
        $gen_edit_config = json_decode($info['gen_edit_config'], true) ?? [];
        $gen_del_config = json_decode($info['gen_del_config'], true) ?? [];
        $gen_search_config = json_decode($info['gen_search_config'], true) ?? [];
        $data[] = $make->createController($base_config);
        $data[] = $make->createLogic($base_config, $gen_search_config);
        $data[] = $make->createService($base_config);
        $data[] = $make->createModel($base_config);
        $data[] = $make->createValidate($base_config, $gen_edit_config);
        $data[] = $make->createIndexVue($base_config);
        $data[] = $make->createTableVue($base_config, $gen_base_config, $gen_search_config, $gen_del_config);
        $data[] = $make->createFromVue($base_config, $gen_edit_config);
        $data[] = $make->createApiTs($base_config, $gen_search_config, $gen_base_config, $gen_edit_config);
        return $data;
    }

    /**
     * 生成代码预览
     * @return array
     */
    public function genPreview(): array
    {
        $name = request()->input('name');
        $name = str_replace(env('DB_PREFIX'), '', $name);
        $data = $this->createCode($name);
        return message($data);
    }

    public function createCodeDownload()
    {
        $name = request()->input('name');
        $name = str_replace(env('DB_PREFIX'), '', $name);
        $data = $this->createCode($name);
        foreach ($data as $item){
          $path=str_replace('bhadmin',$name,$item['path']);
          $create_ptah=public_path('temp/'.$path);
          FileStrategy::createDir($create_ptah);
          file_put_contents($create_ptah.DS.$item['file_name'],$item['content']);
        }
        //压缩文件

        try {
          FileStrategy::zipFolder(public_path('temp/'.$name),public_path('temp/').$name.'.zip');
        }catch (\RuntimeException $e){
            throw new ApiException('下载错误');
        }
        //删除文件夹
        FileStrategy::delDir(public_path('temp/'.$name));

        $downloadName=$name.'.zip';
        return message(['download_name'=>$name,'url'=>siteUrl('/temp/'.$downloadName)]);
    }
}
